use super::file_ops::copy_file;
use super::models::FileData;
use crate::fs_tool::delete_log;
use serde_json::{json, Value};
use std::fs::{self, File};
use std::io::{Seek, SeekFrom, Write};
use std::path::Path;
pub fn add_file_json(_path: &str, _json: &str) -> Result<String, String> {
    let mut entry = serde_json::from_str(_json).map_err(|e| format!("JSON解析失败: {}", e))?;
    //插入修改某个字段
    // if let Value::Object(ref mut map) = entry {
    //     map.insert("name".to_string(), json!("new_name"));
    // }
    if let Value::Object(ref mut map) = entry {
        map.insert("url".to_string(), json!("url"));
    }

    let origin_path = Path::new(_path);
    let temp_path = origin_path.with_extension("tmp");

    let file_data = copy_file(origin_path)?;
    let mut temp_file = file_data.file;

    add_end_obj(&mut temp_file, _json, &entry)?;
    super::file_ops::replace_file(&temp_path, origin_path)?;

    Ok("成功写入".to_string())
}

pub fn delete_file_json(origin_path: &Path, _json: &str) -> Result<String, String> {
    let query: Value = serde_json::from_str(_json).map_err(|e| format!("JSON解析失败: {}", e))?;

    let target_name = query
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or("查询JSON缺少name字段或类型错误")?;

    let contents = fs::read_to_string(origin_path).map_err(|e| format!("文件读取失败: {}", e))?;

    let mut json_array: Vec<Value> = if contents.trim().is_empty() {
        return Err("日志文件为空".into());
    } else {
        serde_json::from_str(&contents).map_err(|e| format!("日志解析失败: {}", e))?
    };

    let original_len = json_array.len();
    json_array.retain(|entry| {
        entry
            .get("name")
            .and_then(|v| v.as_str())
            .map(|name| name != target_name)
            .unwrap_or(true)
    });

    if original_len == json_array.len() {
        return Err(format!("未找到name为'{}'的条目", target_name));
    }

    let new_contents =
        serde_json::to_string_pretty(&json_array).map_err(|e| format!("JSON序列化失败: {}", e))?;

    let temp_path = origin_path.with_extension("tmp");
    fs::write(&temp_path, new_contents).map_err(|e| format!("临时文件写入失败: {}", e))?;

    super::file_ops::replace_file(&temp_path, origin_path)?;
    Ok("成功删除".to_string())
}

pub fn edit_file_json(_path: &str, _json: &str) -> Result<String, String> {
    let origin_path = Path::new(_path);
    let temp_path = origin_path.with_extension("tmp");

    let mut query: Value =
        serde_json::from_str(_json).map_err(|e| format!("JSON解析失败: {}", e))?;

    if let Value::Object(ref mut map) = query {
        map.insert("url".to_string(), json!(""));
    }

    let target_name = query
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or("查询JSON缺少name字段或类型错误")?;

    let contents = fs::read_to_string(origin_path).map_err(|e| format!("文件读取失败: {}", e))?;

    let mut json_array: Vec<Value> = if contents.trim().is_empty() {
        return Err("日志文件为空".into());
    } else {
        serde_json::from_str(&contents).map_err(|e| format!("日志解析失败: {}", e))?
    };

    for element in json_array.iter_mut() {
        if let Some(name) = element.get("name").and_then(|v| v.as_str()) {
            if name == target_name {
                *element = query.clone();
            }
        }
    }

    let new_contents =
        serde_json::to_string_pretty(&json_array).map_err(|e| format!("JSON序列化失败: {}", e))?;

    fs::write(&temp_path, new_contents).map_err(|e| format!("临时文件写入失败: {}", e))?;

    super::file_ops::replace_file(&temp_path, origin_path)?;
    Ok("成功修改".to_string())
}
pub fn delete_user_mes(_path: &Path, _json: &str, path_a: &str) -> Result<String, String> {
    //读取全部的log文件，对比id与user_id相同的项目，执行delete_log
 
    let content = std::fs::read_to_string(_path).map_err(|e| format!("log文件读取失败: {}", e))?;
    let mut log_obj: Vec<Value> =
        serde_json::from_str(&content).map_err(|e| format!("JSON解析失败: {}", e))?;
    let mut json_obj: Value =
        serde_json::from_str(_json).map_err(|e| format!("JSON解析失败: {}", e))?;
    let target_user_id = json_obj
        .get("user_id")
        .ok_or("提供的JSON参数缺少user_id字段")?;
    // let users: Vec<Value> =
    // 遍历处理每个用户
    let mut mes = 'N';


    for user in log_obj {
        if let Some(user_id) = user.get("user_id") {
            if user_id == target_user_id {
                delete_log(path_a, &user.to_string());
            } else {
            }
        }
    }

    Ok(mes.to_string())
}

pub fn add_end_obj(
    mut temp_file: impl Write + Seek,
    _json: &str,
    entry: &Value,
) -> Result<String, String> {
    let file_size = temp_file
        .seek(SeekFrom::End(0))
        .map_err(|e| format!("获取文件大小失败: {}", e))?;

    if file_size != 2 {
        temp_file
            .seek(SeekFrom::End(-1))
            .map_err(|e| format!("文件定位失败: {}", e))?;
        write!(temp_file, ",\n").map_err(|e| format!("分隔符写入失败: {}", e))?;
    } else {
        temp_file
            .seek(SeekFrom::End(-1))
            .map_err(|e| format!("文件定位失败: {}", e))?;
        write!(temp_file, "\n\n").map_err(|e| format!("分隔符写入失败: {}", e))?;
    }

    serde_json::to_writer_pretty(&mut temp_file, &entry)
        .map_err(|e| format!("条目序列化失败: {}", e))?;

    write!(&mut temp_file, "\n]").map_err(|e| format!("闭合符写入失败: {}", e))?;

    Ok("成功写入".to_string())
}
